// 引入Service层
const serviceManager = require("./serviceMapper");
import { request } from "../../utils/request";

Page({
  data: {
    isShow: false,
    selectedService: {},
    familyMembers: [],
    selectedFamily: '',
    selectedDate: '',
    selectedTime: '',
    fullDateTime: '',
    searchValue: '',
    historyList: [],
    filteredServices: [],
    allServices: [],
    isLoading: true // 数据加载状态
  },

  onLoad() {
    this.setData({ historyList: serviceManager.getHistoryList() });
    this.fetchCareItems();
    this.fetchFamilyMembers();
  },

  // 获取护理项目列表
  fetchCareItems() {
    this.setData({ isLoading: true });
    request('/service/item/list1', {}, 'GET')
      .then(res => {
        if (res.code === 200) {
          const dataArray = Array.isArray(res.data) ? res.data : [];
          const activeServices = dataArray
            .filter(item => item.status === 1)
            .map(item => ({
              id: item.id,
              name: item.name || '未知服务',
              price: item.price ? parseFloat(item.price.toString()) : 0,
              unit: item.unit || '次',
              image: item.image || '/img/default-service.png',
              requirements: item.requirements || '暂无护理要求'
            }));

          this.setData({
            allServices: activeServices,
            filteredServices: activeServices,
            isLoading: false
          });
        } else {
          wx.showToast({ title: '获取服务列表失败', icon: 'none' });
          this.setData({ allServices: [], filteredServices: [], isLoading: false });
        }
      })
      .catch(err => {
        wx.showToast({ title: '服务列表加载失败', icon: 'none' });
        console.error('接口请求失败：', err);
        this.setData({ allServices: [], filteredServices: [], isLoading: false });
      });
  },

  // 获取老人列表
  fetchFamilyMembers() {
    request('/Elder/list', {}, 'GET')
      .then(res => {
        if (res.code === 200) {
          const familyNames = res.data.map(elder => elder.name);
          this.setData({ familyMembers: familyNames });
        }
      })
      .catch(err => {
        console.error('获取家人列表失败', err);
      });
  },

  // 输入实时过滤
  onSearchInput(e) {
    const value = e.detail.value.trim();
    this.setData({ searchValue: value });
    const filtered = this.data.allServices.filter(item => 
      item.name.includes(value) || item.requirements.includes(value)
    );
    this.setData({ filteredServices: filtered });
  },

  // 点击历史记录搜索
  selectHistory(e) {
    const keywords = e.currentTarget.dataset.keywords;
    this.setData({ searchValue: keywords });
    const filtered = this.data.allServices.filter(item => 
      item.name.includes(keywords) || item.requirements.includes(keywords)
    );
    this.setData({ filteredServices: filtered });
  },

  // 显示服务弹窗
  showTan(e) {
    const index = e.currentTarget.dataset.index;
    const selectedService = this.data.filteredServices[index];
    this.setData({
      isShow: true,
      selectedService: {
        name: selectedService.name,
        price: selectedService.price,
        unit: selectedService.unit,
        id: selectedService.id,
        desc: selectedService.requirements
      }
    });
  },

  // 回车搜索（添加到历史）
  handleSearch() {
    const { searchValue } = this.data;
    if (!searchValue) return;
    const newHistory = serviceManager.addToHistory(searchValue);
    this.setData({ historyList: newHistory });
  },

  // 取消搜索
  onCancel() {
    this.setData({ searchValue: '' });
  },

  // 清空历史弹窗控制
  showDeleteModal() { this.setData({ showModal: true }); },
  hideModal() { this.setData({ showModal: false, isShow: false }); },
  confirmDelete() {
    const newHistory = serviceManager.clearHistory();
    this.setData({ historyList: newHistory, showModal: false });
  },

  // 跳转到服务详情
  navToServiceDetail(e) {
    const service = e.currentTarget.dataset.service;
    wx.navigateTo({
      url: `/pages/service-detail/service-detail?service=${JSON.stringify(service)}`
    });
  },

  // 选择家人
  onFamilyChange(e) {
    const index = e.detail.value;
    this.setData({ selectedFamily: this.data.familyMembers[index] });
  },

  // 选择日期
  onDateChange(e) {
    this.setData({
      selectedDate: e.detail.value,
      fullDateTime: this.data.selectedTime ? `${e.detail.value} ${this.data.selectedTime}` : ''
    });
  },

  // 选择时间
  onTimeChange(e) {
    this.setData({
      selectedTime: e.detail.value,
      fullDateTime: this.data.selectedDate ? `${this.data.selectedDate} ${e.detail.value}` : ''
    });
  },

  // 确认购买
  confirmPurchase(e) {
    if (!this.data.selectedFamily || !this.data.fullDateTime) {
      wx.showToast({ title: '请完善订单信息', icon: 'none' });
      return;
    }
    const orderData = {
      service: this.data.selectedService,
      family: this.data.selectedFamily,
      time: this.data.fullDateTime,
    };
    wx.navigateTo({
      url: '/pages/confirm-order/confirm-order?orderData=' + JSON.stringify(orderData)
    });
    this.hideModal();
  },
});